package com.avalon.shop.service;

import com.avalon.core.exception.AvalonException;
import com.avalon.core.util.JacksonUtil;
import com.avalon.core.util.RestTemplateUtils;
import com.avalon.shop.ShopContext;
import com.avalon.shop.config.ShopConfig;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ResourceService {
    private final String serviceName = "pet.common.image";
    private final ShopConfig shopConfig;
    private final ShopContext shopContext;

    public ResourceService(ShopConfig shopConfig, ShopContext shopContext) {
        this.shopConfig = shopConfig;
        this.shopContext = shopContext;
    }

    public List<Map> getResourceAll(String type) {
        log.info("getResourceAll type:{},token:{}", type, shopContext.getBackToken());
        HashMap<String, Object> param = new HashMap<>();
        param.put("fields", "id,name,img,type,sequence,key,url,param1,param2");
        param.put("order", "sequence asc, id desc");
        param.put("rpnCondition", "(=,type," + type + ")");
        param.put("serviceName", serviceName);
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        headers.put("token", shopContext.getBackToken());
        headers.put("Accept", MediaType.toString(Arrays.asList(MediaType.APPLICATION_JSON)));
        ResponseEntity<String> responseEntity = RestTemplateUtils.post(
                shopConfig.getServer() + "/model/get/all",
                headers, param, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            List<Map> maps = JacksonUtil.convert2Object(responseEntity.getBody(), new TypeReference<List<Map>>() {
            });
            return maps;
        } else {
            log.error("getResourceAll 错误:" + responseEntity.getBody());
            throw new AvalonException(responseEntity.getBody());
        }
    }
}
